<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1080">
    <el-form
      label-position="top"
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
      :disabled="disabled"
    >

      <!--      <ContentWrap>-->
      <!--        <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">-->
      <!--          <el-tab-pane label="基础信息" name="item">-->
      <el-row :gutter="5">

        <el-col :span="3">
          <el-form-item label="订单时间" prop="orderTime">
            <el-date-picker
              v-model="formData.orderTime"
              type="date"
              value-format="x"
              placeholder="选择订单时间"
              class="!w-1/1"
            />
          </el-form-item>
        </el-col>

        <el-col :span="4">
          <el-form-item label="客户" prop="customerId">
            <el-select
              v-model="formData.customerId"
              clearable
              @change="handleCustomerChange"
              filterable
              placeholder="请选择客户"
              class="!w-1/1"
            >
              <el-option
                v-for="item in customerList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="3">
          <el-form-item label="车牌号" prop="licensePlate">
            <el-input v-model="formData.licensePlate" placeholder="请输入车牌号"/>
          </el-form-item>
        </el-col>

        <el-col :span="4">
          <el-form-item label="收取订金" prop="depositPrice">
            <el-input-number
              v-model="formData.depositPrice"
              controls-position="right"
              :min="0"
              :precision="0"
              placeholder="请输入收取订金"
              class="!w-1/1"
            />
          </el-form-item>
        </el-col>

        <el-col :span="4">
          <el-form-item label="结算账户" prop="accountId">
            <el-select
              v-model="formData.accountId"
              clearable
              filterable
              placeholder="请选择结算账户"
              class="!w-1/1"
            >
              <el-option
                v-for="item in accountList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>


        <el-col :span="8">
          <el-form-item label="备注" prop="remark">
            <el-input
              type="textarea"
              v-model="formData.remark"
              :rows="1"
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="注释" prop="annotationTxt">
            <el-input
              type="textarea"
              v-model="formData.annotationTxt"
              :rows="1"
              placeholder="请输入注释"
            />
          </el-form-item>
        </el-col>

        <!--              <el-col :span="6">-->
        <!--                <el-form-item label="发单操作" prop="remark">-->
        <!--                  <el-button type="primary">确认发单</el-button>-->
        <!--                </el-form-item>-->
        <!--              </el-col>-->
      </el-row>
      <!--          </el-tab-pane>-->
      <!--        </el-tabs>-->
      <!--      </ContentWrap>-->

      <!--      <ContentWrap>-->
      <!--        <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">-->
      <!--          <el-tab-pane label="生成/筛选(仅车型)产品" name="item">-->
      <!--            <el-row :gutter="5">-->
      <!--              <el-col :span="6">-->
      <!--                <el-form-item label="订单类型" prop="productType">-->
      <!--                  <el-select-->
      <!--                    v-model="formData.productType"-->
      <!--                    placeholder="请选择订单类型"-->
      <!--                    clearable-->
      <!--                    style="width: 240px"-->
      <!--                  >-->
      <!--                    <el-option-->
      <!--                      v-for="item in productTypeOptions"-->
      <!--                      :key="item.value"-->
      <!--                      :label="item.label"-->
      <!--                      :value="item.value"-->
      <!--                    />-->
      <!--                  </el-select>-->
      <!--                </el-form-item>-->
      <!--              </el-col>-->
      <!--              <el-col :span="8">-->
      <!--                <el-form-item label="VIN" prop="vin">-->

      <!--                  <el-input-->
      <!--                    v-model="formData.vin"-->
      <!--                    style="max-width: 600px"-->
      <!--                    placeholder="请输入VIN"-->
      <!--                    class="input-with-select"-->
      <!--                  >-->
      <!--                    <template #append>-->
      <!--                      <el-button @click="handleJyCarTypeByVin" type="success">搜索车型</el-button>-->
      <!--                    </template>-->
      <!--                  </el-input>-->
      <!--                </el-form-item>-->
      <!--              </el-col>-->

      <!--              <el-col :span="10">-->
      <!--                <el-form-item label="车型" prop="typeCar">-->
      <!--                  <el-input @change="handleTypeCarChange" v-model="formData.typeCar"-->
      <!--                            placeholder="请输入车型"/>-->
      <!--                </el-form-item>-->
      <!--              </el-col>-->

      <!--              <el-col :span="24">-->
      <!--                <el-row :gutter="10">-->
      <!--                  <el-col :span="6">-->
      <!--                    <el-form-item label="部位" prop="saleType">-->
      <!--                      <el-select v-model="formData.saleType" @change="handleSaleTypeChange"-->
      <!--                                 placeholder="请选择部位" clearable>-->
      <!--                        <el-option-->
      <!--                          v-for="dict in getStrDictOptions(DICT_TYPE.ERP_SALE_TYPE)"-->
      <!--                          :key="dict.value"-->
      <!--                          :label="dict.label"-->
      <!--                          :value="dict.value"-->
      <!--                        />-->
      <!--                      </el-select>-->
      <!--                    </el-form-item>-->
      <!--                  </el-col>-->
      <!--                  <el-col :span="4" v-show="formData.oe !=undefined && formData.oe.length >0">-->
      <!--                    <el-form-item label="OE码" prop="saleType">-->
      <!--                      <el-text class="mx-1" type="success">{{ formData.oe }}</el-text>-->
      <!--                    </el-form-item>-->
      <!--                  </el-col>-->

      <!--                  <el-col :span="4">-->
      <!--                    <el-form-item label="品牌" prop="glassBrand">-->
      <!--                      <el-select v-model="formData.glassBrand" @change="handleBrandChange"-->
      <!--                                 placeholder="请选择品牌" clearable>-->
      <!--                        <el-option-->
      <!--                          v-for="dict in getStrDictOptions(DICT_TYPE.ERP_GLASS_BRAND)"-->
      <!--                          :key="dict.value"-->
      <!--                          :label="dict.label"-->
      <!--                          :value="dict.value"-->
      <!--                        />-->
      <!--                      </el-select>-->
      <!--                    </el-form-item>-->
      <!--                  </el-col>-->

      <!--                  <el-col :span="4">-->
      <!--                    <el-form-item label="创建产品" prop="">-->
      <!--                      <el-tooltip-->
      <!--                        class="box-item"-->
      <!--                        effect="dark"-->
      <!--                        content="根据基础信息生成产品信息"-->
      <!--                        placement="top-start"-->
      <!--                      >-->
      <!--                        <el-button type="primary" @click="handleCreateProduct" round>生成产品信息-->
      <!--                        </el-button>-->
      <!--                      </el-tooltip>-->
      <!--                    </el-form-item>-->
      <!--                  </el-col>-->
      <!--                </el-row>-->

      <!--              </el-col>-->


      <!--            </el-row>-->

      <!--            <el-row :gutter="10">-->
      <!--              <el-col :span="8">-->
      <!--                <el-form-item label="工厂产品名称" prop="factoryName">-->
      <!--                  <el-input v-model="formData.factoryName"-->
      <!--                            placeholder="请输入工厂产品名称"/>-->
      <!--                </el-form-item>-->
      <!--              </el-col>-->
      <!--              <el-col :span="8">-->
      <!--                <el-form-item label="工厂编号" prop="factoryNumber">-->
      <!--                  <el-input v-model="formData.factoryNumber"-->
      <!--                            @change="handleFactoryNumberChange"-->
      <!--                            placeholder="请输入工厂编号">-->
      <!--                    <template #append>-->
      <!--                      <el-button @click="handleSyncFactoryNumber" type="success">同 步</el-button>-->
      <!--                    </template>-->
      <!--                  </el-input>-->
      <!--                </el-form-item>-->
      <!--              </el-col>-->
      <!--            </el-row>-->


      <!--          </el-tab-pane>-->
      <!--        </el-tabs>-->
      <!--      </ContentWrap>-->


      <el-row :gutter="20">
        <el-col :span="24">
          <!-- 子表的表单 -->
          <ContentWrap>
            <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">
              <el-tab-pane label="订单产品清单" name="item">
                <SaleOrderItemForm ref="itemFormRef" :items="formData.items" :disabled="disabled"
                                   :amSeriesName="formData.amSeriesName" :oe="formData.oe"
                                   :brandId="formData.glassBrand"
                                   :factoryNumber="formData.factoryNumber"/>
              </el-tab-pane>
            </el-tabs>
          </ContentWrap>
        </el-col>
      </el-row>

      <el-collapse v-model="activeName" accordion>

        <el-collapse-item title="提成费用" name="1">
          <ContentWrap>
            <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">
              <el-tab-pane label="状态跟踪" name="item">
                <el-row :gutter="20">
                  <el-col :span="24">
                    <el-steps :active="5" finish-status="success">
                      <el-step title="待采购" description="2018/4/3 20:46"/>
                      <el-step title="预约客户" description="2018/4/3 20:46"/>
                      <el-step title="采购完成" description="2018/4/3 20:46"/>
                      <el-step title="完工" description="2018/4/3 20:46"/>
                      <el-step title="发单" description="2018/4/3 20:46"/>
                      <el-step title="对账" description="2018/4/3 20:46"/>
                      <el-step title="收款" description="2018/4/3 20:46"/>
                    </el-steps>
                  </el-col>
                </el-row>

              </el-tab-pane>
            </el-tabs>
          </ContentWrap>

          <!--      销售和渠道提成-->
          <el-row :gutter="10">
            <el-col :span="12">
              <ContentWrap>
                <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">
                  <el-tab-pane label="销售提成" name="item">
                    <el-col :span="8">
                      <el-switch
                        @change="saleCostTypeChange"
                        v-model="formData.saleCostType"
                        active-text=""
                        inactive-text="固定费用"/>
                    </el-col>

                    <el-row :gutter="10">
                      <el-col :span="12">
                        <el-form-item label="销售人员" prop="saleUserId">
                          <el-select
                            v-model="formData.saleUserId"
                            @change="saleUserChange"
                            clearable
                            filterable
                            placeholder="请选择销售人员"
                            class="!w-1/1"
                          >
                            <el-option
                              v-for="item in saleUserList"
                              :key="item.id"
                              :label="item.nickname"
                              :value="item.id"
                            />
                          </el-select>
                        </el-form-item>
                      </el-col>

                      <el-col :span="6"
                              v-if="formData.saleUserId !=undefined && !formData.saleCostType && formData.saleUserCost >0">
                        <el-form-item label="提成比例" prop="">
                          <el-text class="mx-1" type="success">{{ saleRate }}%</el-text>
                        </el-form-item>
                      </el-col>
                      <el-col :span="6"
                              v-if="formData.saleUserId !=undefined && !formData.saleCostType && formData.saleUserCost >0">
                        <el-form-item label="提成金额(元)" prop="">
                          <el-text class="mx-1" type="success">{{ formData.saleUserCost }}</el-text>
                        </el-form-item>
                      </el-col>

                      <el-col :span="12" v-if="formData.saleCostType">
                        <el-form-item label="提成金额" prop="saleUserCost">
                          <el-input type="number" v-model="formData.saleUserCost"
                                    placeholder="请输入提成金额"/>
                        </el-form-item>
                      </el-col>
                    </el-row>


                  </el-tab-pane>
                </el-tabs>
              </ContentWrap>
            </el-col>

            <el-col :span="12">
              <ContentWrap>
                <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">
                  <el-tab-pane label="渠道提成" name="item">
                    <el-col :span="8">
                      <el-switch
                        @change="channelCostTypeChange"
                        v-model="formData.channelCostType"
                        active-text=""
                        inactive-text="固定费用"/>
                    </el-col>
                    <el-row :gutter="10">
                      <el-col :span="12">
                        <el-form-item label="渠道人员" prop="channelUserId">
                          <el-select
                            v-model="formData.channelUserId"
                            @change="channelUserChange"
                            clearable
                            filterable
                            placeholder="请选择渠道人员"
                            class="!w-1/1"
                          >
                            <el-option
                              v-for="item in channelUserList"
                              :key="item.id"
                              :label="item.nickname"
                              :value="item.id"
                            />
                          </el-select>
                        </el-form-item>
                      </el-col>

                      <el-col :span="6"
                              v-if="formData.channelUserId !=undefined && !formData.channelCostType && formData.channelCost >0">
                        <el-form-item label="提成比例" prop="">
                          <el-text class="mx-1" type="success">{{ channelRate }}%</el-text>
                        </el-form-item>
                      </el-col>
                      <el-col :span="6"
                              v-if="formData.channelUserId !=undefined && !formData.channelCostType && formData.channelCost >0">
                        <el-form-item label="提成金额(元)" prop="">
                          <el-text class="mx-1" type="success">{{ formData.channelCost }}</el-text>
                        </el-form-item>
                      </el-col>

                      <el-col :span="12" v-if="formData.channelCostType">
                        <el-form-item label="提成金额" prop="channelCost">
                          <el-input type="number" v-model="formData.channelCost"
                                    placeholder="请输入提成金额"/>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-tab-pane>
                </el-tabs>
              </ContentWrap>
            </el-col>
          </el-row>

          <!--技师和外协费用-->
          <el-switch v-model="hasOutSource" active-text="" inactive-text="是否有外协"/>
          <div style="clear: both"></div>
          <el-row :gutter="10">
            <!-- 技师提成表单 -->
            <el-col :span="12">
              <ContentWrap>
                <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">
                  <el-tab-pane label="技师提成" name="item">
                    <SaleOrderEngineerForm ref="engineerFormRef" :items="formData.engineerList"
                                           :disabled="disabled"/>
                  </el-tab-pane>
                </el-tabs>
              </ContentWrap>
            </el-col>
            <!--外协费用 -->
            <el-col :span="12">
              <ContentWrap v-show="disabled || hasOutSource">
                <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">
                  <el-tab-pane label="外协服务费用" name="item">
                    <SaleOrderOutsourceForm ref="formOutRef" :items="formData.outsourceList"
                                            :disabled="disabled"/>
                  </el-tab-pane>
                </el-tabs>
              </ContentWrap>
            </el-col>
          </el-row>

          <!--其他费用 -->
          <el-row :gutter="10">
            <el-col :span="12">
              <ContentWrap>
                <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">
                  <el-tab-pane label="其他费用" name="item">
                    <SaleOrderOtherCostForm ref="formOtherCostRef" :items="formData.otherCostList"
                                            :disabled="disabled"/>
                  </el-tab-pane>
                </el-tabs>
              </ContentWrap>
            </el-col>
            <el-col :span="12">
              <el-form-item label="图片信息" prop="imgUrls">
                <UploadImgs :disabled="isDetail" v-model="formData.imgUrls"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>
      </el-collapse>


      <!--车妈妈相关-->
      <ContentWrap v-if="CMMCustomer">
        <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">
          <el-tab-pane label="车妈妈相关资料" name="item">
            <el-form
              label-position="top">
              <el-row :gutter="5">
                <!--车妈妈-->
                <el-col :span="8">
                  <el-form-item label="施工图" prop="imgUrls">
                    <UploadImg :disabled="isDetail" v-model="formData.cmmBuildPic"/>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="人车合一照" prop="imgUrls">
                    <UploadImg :disabled="isDetail" v-model="formData.cmmGroupPic"/>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </ContentWrap>

      <!--玖达相关资料-->
      <ContentWrap v-if="JDCustomer">
        <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">
          <el-tab-pane label="玖达相关资料" name="item">
            <el-form
              label-position="top">
              <el-row :gutter="24">
                <!--玖达-->
                <el-col :span="8">
                  <el-form-item label="车架号" prop="imgUrls">
                    <UploadImg :disabled="isDetail" v-model="formData.jdFrameNoPic"/>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="车前图片" prop="imgUrls">
                    <UploadImg :disabled="isDetail" v-model="formData.jdFrontPic"/>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="车后图片" prop="imgUrls">
                    <UploadImg :disabled="isDetail" v-model="formData.jdRearPic"/>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="破损点图片" prop="imgUrls">
                    <UploadImg :disabled="isDetail" v-model="formData.jdDamagePic"/>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="扩损点图" prop="imgUrls">
                    <UploadImg :disabled="isDetail" v-model="formData.jdExpansionPic"/>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="空窗图" prop="imgUrls">
                    <UploadImg :disabled="isDetail" v-model="formData.jdBlankPic"/>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="原车玻璃LOGO图" prop="imgUrls">
                    <UploadImg :disabled="isDetail" v-model="formData.jdPreLogoPic"/>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="更换玻璃LOGO图" prop="imgUrls">
                    <UploadImg :disabled="isDetail" v-model="formData.jdAfterLogoPic"/>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="完工图" prop="imgUrls">
                    <UploadImg :disabled="isDetail" v-model="formData.jdFinishPic"/>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="驾驶证" prop="imgUrls">
                    <UploadImg :disabled="isDetail" v-model="formData.jdDrivingLicensePic"/>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="行驶证" prop="imgUrls">
                    <UploadImg :disabled="isDetail" v-model="formData.jdRunPic"/>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="电子保单" prop="imgUrls">
                    <UploadImg :disabled="isDetail" v-model="formData.jdPolicyPic"/>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </ContentWrap>


    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading" v-if="!disabled">
        确 定
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">

import {DICT_TYPE, getIntDictOptions, getStrDictOptions} from '@/utils/dict'
import {ProductApi, ProductVO} from '@/api/erp/product/product'
import {SaleOrderApi, SaleOrderVO} from '@/api/erp/sale/order'
import SaleOrderItemForm from './components/SaleOrderItemForm.vue'
import {CustomerApi, CustomerVO} from '@/api/erp/sale/customer'
import {AccountApi, AccountVO} from '@/api/erp/finance/account'
import {erpPriceInputFormatter, erpPriceMultiply} from '@/utils'
import * as UserApi from '@/api/system/user'
import SaleOrderEngineerForm from "@/views/erp/sale/order/components/SaleOrderEngineerForm.vue";//技师
import SaleOrderOutsourceForm from "@/views/erp/sale/order/components/SaleOrderOutsourceForm.vue";//外协
import SaleOrderOtherCostForm from "@/views/erp/sale/order/components/SaleOrderOtherCostForm.vue";//其他费用
import {ElMessage, ElLoading} from 'element-plus'

const activeName = ref('2')
/** ERP 销售订单表单 */
defineOptions({name: 'SaleOrderForm'})

const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示


const saleRate = ref() //销售比例
const channelRate = ref(0) //渠道比例

const hasOutSource = ref(false) //是否有外协
const saleUserList = ref([]) //销售人员list
const channelUserList = ref([]) //渠道人员list
const JDCustomer = ref(false) //是否是玖达
const CMMCustomer = ref(false) //是否是车妈妈
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改；detail - 详情


const formData = ref({
  id: undefined,
  customerId: undefined,
  saleType: undefined,
  accountId: undefined,
  saleUserId: undefined,
  orderTime: undefined,
  remark: undefined,
  annotationTxt:undefined,
  fileUrl: '',
  discountPercent: 0,
  discountPrice: 0,
  totalPrice: 0,
  depositPrice: undefined,
  items: [],//订单项
  glassBrand: undefined,//玻璃品牌
  vin: undefined,
  oe: undefined,//原厂零件号
  factoryNumber: undefined,//工厂编号
  factoryName: undefined,//工厂产品名称
  amMainBrandName: undefined,//一级品牌名称
  amBrandName: undefined,//二级品牌名称
  amSeriesId: undefined,//车系ID
  amSeriesName: undefined,//车系名称
  amVehicleName: undefined,//销售车型名称
  amVehicleId: undefined,//销售车型ID
  amYear: undefined,//年份
  outsourceList: [],//外协
  otherCostList: [],//其他费用
  engineerList: [],//参与技师
  imgUrls: [],//图片信息
  licensePlate: undefined,//车牌号
  typeCar: undefined,//车型
  productType: undefined,//产品类型
  allRoyalty: 0,//总提成
  channelCostType: false,
  saleCostType: false,
  no: undefined, // 订单单号，后端返回
  saleUserCost: undefined,//销售人员提成
  channelCost: undefined,//渠道人员费用
  channelUserId: undefined,//渠道人员ID
  //车妈妈相关资料
  cmmBuildPic: '',//施工图
  cmmGroupPic: '',//人车合一照
  //玖达相关资料
  jdFrameNoPic: '',
  jdFrontPic: '',
  jdRearPic: '',
  jdDamagePic: '',
  jdExpansionPic: '',
  jdBlankPic: '',
  jdPreLogoPic: '',
  jdAfterLogoPic: '',
  jdFinishPic: '',
  jdDrivingLicensePic: '',
  jdRunPic: '',
  jdPolicyPic: '',
})

import {ref, provide} from 'vue';
import {EngineerApi} from "@/api/erp/engineer";
import form from "@/components/Form/src/Form.vue";

provide('saleOrderForm', formData.value);

const formRules = reactive({
  customerId: [{required: true, message: '客户不能为空', trigger: 'blur'}],
  orderTime: [{required: true, message: '订单时间不能为空', trigger: 'blur'}]
})


let disabled = undefined;
if (computed) {
  disabled = computed(() => formType.value === 'detail')
}
const formRef = ref() // 表单 Ref
const customerList = ref<CustomerVO[]>([]) // 客户列表
const accountList = ref<AccountVO[]>([]) // 账户列表
const userList = ref<UserApi.UserVO[]>([]) // 用户列表

/** 子表的表单 */
const subTabsName = ref('item')
//订单项
const itemFormRef = ref()
//技师
const engineerFormRef = ref()
//外协
const formOutRef = ref()
//其他费用
const formOtherCostRef = ref()

if (watch) {
  /** 计算 discountPrice、totalPrice 价格 */
  watch(
    () => formData.value,
    (val) => {
      if (!val) {
        return
      }
      const totalPrice = val.items.reduce((prev, curr) => prev + curr.totalPrice, 0)
      const discountPrice =
        val.discountPercent != null ? erpPriceMultiply(totalPrice, val.discountPercent / 100.0) : 0
      if (typeof discountPrice === "number") {
        formData.value.discountPrice = discountPrice;
      }
      formData.value.totalPrice = totalPrice - discountPrice;

      //处理销售和渠道佣金问题
      if (formData.value.items.length > 0 && formData.value.items[0].productPrice > 0) {

        let allPrice = 0;
        for (let i = 0; i < formData.value.items.length; i++) {
          allPrice = allPrice + formData.value.items[i].totalPrice;
        }

        if (!formData.value.channelCostType) {
          //渠道佣金
          formData.value.channelCost = allPrice * channelRate.value / 100;
        }
        if (!formData.value.saleCostType) {
          //销售佣金
          formData.value.saleUserCost = allPrice * saleRate.value / 100;
        }
      }

      if (formData.value.typeCar != undefined) {
        // getProductList(undefined);
      }
    },
    {deep: true}
  )
}


//根据vin获取车型
const handleJyCarTypeByVin = async () => {
  const vinVal = formData.value.vin;
  if (vinVal == undefined || vinVal.length != 17) {
    ElMessage.error('请输入正确的17位VIN');
    return;
  }

  const loading = ElLoading.service({
    lock: true,
    text: '车型查询中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  const data = await SaleOrderApi.getJyCarTypeByVin(vinVal);


  if (data == null) {
    formData.value.typeCar = undefined;
    formData.value.productType = undefined;
    formData.value.amVehicleId = undefined;
    formData.value.amMainBrandName = undefined;
    formData.value.amBrandName = undefined;
    formData.value.amSeriesName = undefined;
    formData.value.amSeriesId = undefined;
    formData.value.amVehicleName = undefined;
    ElMessage.error('未查询到车型信息,请检查VIN是否正确');
  } else {
    //车型
    formData.value.typeCar = data.amBrandName + data.amSeriesName + '-' + data.amYear + '款';
    //销售车型ID
    formData.value.amVehicleId = data.amVehicleId;

    formData.value.amMainBrandName = data.amMainBrandName;
    formData.value.amBrandName = data.amBrandName;
    formData.value.amSeriesName = data.amSeriesName;
    formData.value.amSeriesId = data.amSeriesId;
    formData.value.amVehicleName = data.amVehicleName;
    formData.value.amYear = data.amYear;
  }
  setTimeout(() => {
    loading.close()
  }, 500)
}

const getProductList = async (name) => {

  itemFormRef.value.productList = [];


  let queryParams = null;
  if (name != undefined) {
    queryParams = {
      name: name
    }
  } else {
    queryParams = {
      name: formData.value.amSeriesName == undefined ? formData.value.typeCar : formData.value.amSeriesName//名称包含车系，模糊查询
    }
  }


  const data = await ProductApi.getProductPage(queryParams)
  const dataList = data.list;
  for (const key in dataList) {
    let getName = '';
    if (dataList[key].brandName != undefined && dataList[key].brandName != "") {
      getName = "【" + dataList[key].brandName + "】";
      getName = getName + dataList[key].name;
    }
    if (dataList[key].businessTypeName != undefined && dataList[key].businessTypeName != "") {
      getName = getName + dataList[key].businessTypeName;
    }
    dataList[key].name = getName;
  }

  if (dataList.length == 0) {
    formData.value.items[0].productId = undefined;
  }

  //加载对应产品信息
  itemFormRef.value.productList = dataList;
}

//刚才编码
const handleFactoryNumberChange = async () => {

  // getProductList()


}

const handleBrandChange = async () => {
  // getProductList()
}

const handleTypeCarChange = async () => {

  // getProductList(formData.value.typeCar);

}


//选择渠道人员
const channelUserChange = async (e) => {
  if (formData.value.channelUserId == undefined) {
    formData.value.channelCost = 0;
  }
  if (formData.value.channelCostType) {
    return;
  }


  //渠道提成
  if (formData.value.items.length > 0 && formData.value.items[0].productPrice > 0) {
    const getChannelList = channelUserList.value;

    for (const eKey in getChannelList) {
      if (getChannelList[eKey].id == e) {
        //比例
        channelRate.value = getChannelList[eKey].commissionRate;
        let allPrice = 0;
        for (let i = 0; i < formData.value.items.length; i++) {
          allPrice = allPrice + formData.value.items[i].totalPrice;
        }
        let rate = channelRate.value / 100;
        formData.value.channelCost = allPrice * rate;
      }
    }
  }
}

//选择销售人员
function saleUserChange(e) {

  if (formData.value.saleUserId == undefined) {
    formData.value.saleUserCost = 0;
  }

  if (formData.value.saleCostType) {
    return;
  }


  //销售提成
  if (formData.value.items.length > 0 && formData.value.items[0].productPrice > 0) {
    const getSaleList = saleUserList.value;
    for (const eKey in getSaleList) {
      if (getSaleList[eKey].id == e) {
        saleRate.value = getSaleList[eKey].commissionRate;

        let allPrice = 0;
        for (let i = 0; i < formData.value.items.length; i++) {
          allPrice = allPrice + formData.value.items[i].totalPrice;
        }
        formData.value.saleUserCost = allPrice * saleRate.value / 100;
      }
    }
  }
}


const productInfo = ref({
  name: undefined,
  brandId: undefined,
  oe: undefined,
  amMainBrandName: undefined,
  factoryName: undefined,//工厂产品名称
  amBrandName: undefined,
  amSeriesName: undefined,
  amSeriesId: undefined,
  amVehicleName: undefined,
  amYear: undefined,
  businessType: undefined,
  barCode: undefined,
  categoryId: undefined,
  unitId: undefined,
  status: undefined
})
//创建产品信息
const handleCreateProduct = async () => {
  productInfo.value.name = formData.value.typeCar;

  if (formData.value.productType != undefined || formData.value.productType.length > 0) {
    if (formData.value.productType != '玻璃') {
      productInfo.value.name = formData.value.productType;
    }
  }

  productInfo.value.brandId = formData.value.glassBrand;
  productInfo.value.oe = formData.value.oe;
  productInfo.value.amMainBrandName = formData.value.amMainBrandName;
  productInfo.value.amBrandName = formData.value.amBrandName;
  productInfo.value.amSeriesName = formData.value.amSeriesName;
  productInfo.value.amSeriesId = formData.value.amSeriesId;
  productInfo.value.amVehicleName = formData.value.amVehicleName;
  productInfo.value.amYear = formData.value.amYear;
  //工厂编号
  productInfo.value.factoryNumber = formData.value.factoryNumber;
  productInfo.value.businessType = formData.value.saleType;
  productInfo.value.barCode = '-';
  productInfo.value.categoryId = '87';
  productInfo.value.unitId = '3';
  productInfo.value.status = 0;

  if (productInfo.value.name == undefined || productInfo.value.name.length == 0) {
    ElMessage.error('请输入车型信息');
    return;
  }
  if (productInfo.value.brandId == undefined || productInfo.value.brandId.length == 0) {
    ElMessage.error('请选择品牌信息');
    return;
  }
  if (productInfo.value.businessType == undefined || productInfo.value.businessType.length == 0) {
    ElMessage.error('请选择业务类型');
    return;
  }

  const data = productInfo.value as unknown as ProductVO

  const loading = ElLoading.service({
    lock: true,
    text: '生成产品中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  try {
    const r = await ProductApi.createProduct(data);
    if (r > 0) {
      //更新产品信息
      getProductList(undefined);
      //更新产品列表
      ElMessage({
        message: '产品生成成功！',
        type: 'success',
      })
    }
  } finally {
    setTimeout(() => {
      loading.close()
    }, 500)
  }

}

//同步工厂编号
const handleSyncFactoryNumber = async () => {

  if (formData.value.factoryNumber == undefined || formData.value.factoryNumber.length == 0) {
    ElMessage.error('请检查工厂编号');
    return;
  }
  if (formData.value.oe == undefined || formData.value.oe.length == 0) {
    ElMessage.error('请检查OE');
    return;
  }

  let productVO = {
    factoryNumber: formData.value.factoryNumber,
    oe: formData.value.oe,
    factoryName: formData.value.factoryName//工厂产品名称
  }

  const loading = ElLoading.service({
    lock: true,
    text: '同步中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  try {
    await ProductApi.syncProductFactoryNumberByOE(productVO);
    ElMessage({
      message: '同步成功！',
      type: 'success',
    })
  } finally {
    setTimeout(() => {
      loading.close()
    }, 500)
  }
}


/** 打开弹窗 */
const open = async (type: string, id?: number) => {

  saleUserList.value = [];
  channelUserList.value = [];

  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await SaleOrderApi.getSaleOrder(id)

      if (formData.value.engineerList == null) {
        formData.value.engineerList = [];
      }
      if (formData.value.otherCostList == null) {
        formData.value.otherCostList = [];
      }
      if (formData.value.outsourceList == null) {
        formData.value.outsourceList = [];
      }


    } finally {
      formLoading.value = false
    }
  }

  // 加载客户列表
  customerList.value = await CustomerApi.getCustomerSimpleList()
  // 加载用户列表
  userList.value = await UserApi.getSimpleUserList()


  let customer = customerList.value.find(item => item.id === formData.value.customerId)
  if (customer != undefined) {
    if (customer.name === '车妈妈') {
      CMMCustomer.value = true;
      JDCustomer.value = false;
    } else if (customer.name === '玖达') {
      JDCustomer.value = true;
      CMMCustomer.value = false;
    } else {
      CMMCustomer.value = false;
      JDCustomer.value = false;
    }
  }


  //渠道和销售人员
  const getUserList = userList.value;
  for (const userKey in getUserList) {
    const deptName = getUserList[userKey].deptName;
    if (deptName != null) {
      if (deptName.includes('销售')) {
        saleUserList.value.push(getUserList[userKey])
      }
      if (deptName.includes('渠道')) {
        channelUserList.value.push(getUserList[userKey])
      }
    }

  }

  // 加载账户列表
  accountList.value = await AccountApi.getAccountSimpleList()

  const defaultAccount = accountList.value.find((item) => item.defaultStatus)
  if (defaultAccount) {
    formData.value.accountId = defaultAccount.id
  }

  //是否有外协
  if (formData.value.outsourceList == null) {
    formData.value.outsourceList = [];
  }
  if (formData.value.outsourceList.length > 0) {
    hasOutSource.value = true;
  } else {
    hasOutSource.value = false;
  }

}
defineExpose({open}) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {


  if (formData.value.customerId == undefined || formData.value.customerId.length == 0) {
    ElMessage.error('请选择客户信息');
    return;
  }


  if (formData.value.saleUserCost == null) {
    formData.value.saleUserCost = 0;
  }
  if (formData.value.saleUserId != undefined && formData.value.saleUserCost == 0) {
    ElMessage.error('请输入销售员提成');
    return;
  }

  if (formData.value.channelCost == null) {
    formData.value.channelCost = 0;
  }
  if (formData.value.channelUserId != undefined && formData.value.channelCost == 0) {
    ElMessage.error('请输入渠道费用');
    return;
  }


  for (let i = 0; i < formData.value.items.length; i++) {
    const item = formData.value.items[i];
    if (item.productId == undefined || item.productId.length == 0) {
      ElMessage.error('请选择产品');
      return;
    }
  }

  // 校验表单
  await formRef.value.validate()
  await itemFormRef.value.validate()
  await engineerFormRef.value.validate()
  // await formOutRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {

    //校验库存数量 是否有充足库存
    if (formData.value.items.length == 0) {
      ElMessage.error('请添加产品信息');
      return;
    }
    //校验销售价格、供应商、采购
    //  for (let i = 0; i < formData.value.items.length; i++) {
    //    const item = formData.value.items[i];
    //    if (item.productPrice == undefined || item.productPrice.length == 0) {
    //      ElMessage.error('请完善销售价格');
    //      return;
    //    }
    //    if (item.supplierId == undefined || item.supplierId.length == 0) {
    //      ElMessage.error('请完善供应商');
    //      return;
    //   }
    //    //采购价
    //    if (item.purchasePrice == undefined || item.purchasePrice.length == 0) {
    //      ElMessage.error('请完善采购价格');
    //      return;
    //    }
    // }

    const data = formData.value as unknown as SaleOrderVO
    if (formType.value === 'create') {

      await SaleOrderApi.createSaleOrder(data)
      message.success(t('common.createSuccess'))
    } else {
      await SaleOrderApi.updateSaleOrder(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
/**
 * 销售人员提成类型
 * @param e
 */
const saleCostTypeChange = async (e) => {
  if (!e) {
    formData.value.saleUserCost = 0;
  } else {
    formData.value.saleUserCost = undefined;
  }
  formData.value.saleCostType = e;
}

/**
 * 销售类型
 * @param e
 */
// const handleSaleTypeChange = async (e) => {
//   const saleTypeList = getStrDictOptions(DICT_TYPE.ERP_SALE_TYPE);
//   //产品列表
//   getProductList(undefined);
//   for (const eKey in saleTypeList) {
//     if (saleTypeList[eKey].value === e) {
//       const name = saleTypeList[eKey].label;
//       //获取oe码
//       if (name.includes('玻璃')) {
//         const amVehicleId = formData.value.amVehicleId;
//         if (amVehicleId != undefined && amVehicleId.length > 0) {
//
//           const loading = ElLoading.service({
//             lock: true,
//             text: 'OE码查询中...',
//             background: 'rgba(0, 0, 0, 0.7)',
//           })
//
//           const data = await SaleOrderApi.getStdPartNameByAmVehicleId(formData.value.amVehicleId, name);
//
//           if (data == null) {
//             ElMessage.error('未查询OE码信息');
//           } else {
//             formData.value.oe = data.oe;
//           }
//
//           setTimeout(() => {
//             loading.close()
//           }, 500)
//         }
//       }
//     }
//   }
// }

/**
 * 渠道费用类型
 * @param e
 */
const channelCostTypeChange = async (e) => {
  if (!e) {
    formData.value.channelCost = 0;
  } else {
    formData.value.channelCost = undefined;
  }

  formData.value.channelCostType = e;
}


//监听formData.customerId
// watch(() => formData.value.customerId, (newValue, oldValue) => {
//   if (newValue != undefined && newValue.length > 0) {
//     const customer = customerList.value.find(item => item.id === newValue)
//     if (customer.name === '车妈妈') {
//       CMMCustomer.value = true;
//       JDCustomer.value = false;
//     } else if (customer.name === '玖达') {
//       JDCustomer.value = true;
//      CMMCustomer.value = false;
//     } else {
//       CMMCustomer.value = false;
//       JDCustomer.value = false;
//     }
//   }
// })


/**
 * 客户类型选择
 * @param e
 */
const handleCustomerChange = async (e) => {
  let customer = customerList.value.find(item => item.id === e)
  if (customer.name === '车妈妈') {
    CMMCustomer.value = true;
    JDCustomer.value = false;
  } else if (customer.name === '玖达') {
    JDCustomer.value = true;
    CMMCustomer.value = false;
  } else {
    CMMCustomer.value = false;
    JDCustomer.value = false;
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {

    id: undefined,
    customerId: undefined,
    saleType: undefined,
    accountId: undefined,
    saleUserId: undefined,
    orderTime: undefined,
    remark: undefined,
    annotationTxt:undefined,
    fileUrl: '',
    discountPercent: 0,
    discountPrice: 0,
    totalPrice: 0,
    depositPrice: undefined,
    items: [],//订单项
    glassBrand: undefined,//玻璃品牌
    vin: undefined,
    oe: undefined,//原厂零件号
    factoryNumber: undefined,//工厂编号
    factoryName: undefined,//工厂产品名称
    amMainBrandName: undefined,//一级品牌名称
    amBrandName: undefined,//二级品牌名称
    amSeriesId: undefined,//车系ID
    amSeriesName: undefined,//车系名称
    amVehicleName: undefined,//销售车型名称
    amVehicleId: undefined,//销售车型ID
    amYear: undefined,//年份
    outsourceList: [],//外协
    otherCostList: [],//其他费用
    engineerList: [],//参与技师
    imgUrls: [],//图片信息
    licensePlate: undefined,//车牌号
    typeCar: undefined,//车型
    productType: undefined,//产品类型
    allRoyalty: 0,//总提成
    channelCostType: false,
    saleCostType: false,
    no: undefined, // 订单单号，后端返回
    saleUserCost: undefined,//销售人员提成
    channelCost: undefined,//渠道人员费用
    channelUserId: undefined,//渠道人员ID
    //车妈妈相关资料
    cmmBuildPic: '',//施工图
    cmmGroupPic: '',//人车合一照
    //玖达相关资料
    jdFrameNoPic: '',
    jdFrontPic: '',
    jdRearPic: '',
    jdDamagePic: '',
    jdExpansionPic: '',
    jdBlankPic: '',
    jdPreLogoPic: '',
    jdAfterLogoPic: '',
    jdFinishPic: '',
    jdDrivingLicensePic: '',
    jdRunPic: '',
    jdPolicyPic: ''

    // id: undefined,
    // customerId: undefined,
    // accountId: undefined,
    // saleType: undefined,
    // saleUserId: undefined,
    // orderTime: undefined,
    // remark: undefined,
    // fileUrl: undefined,
    // discountPercent: 0,
    // discountPrice: 0,
    // totalPrice: 0,
    // depositPrice: undefined,
    // glassBrand: undefined,//玻璃品牌
    // oe: undefined,//原厂零件号
    // amMainBrandName: undefined,//一级品牌名称
    // amBrandName: undefined,//二级品牌名称
    // amSeriesId: undefined,//车系ID
    // amSeriesName: undefined,//车系名称
    // amVehicleName: undefined,//销售车型名称
    // amYear: undefined,//年份
    // vin: undefined,
    // amVehicleId: undefined,//销售车型ID
    // items: [],//产品清单
    // channelCostType: false,
    // saleCostType: false,
    // outsourceList: [],//外协
    // otherCostList: [],//其他费用
    // engineerList: [],//参与技师
    // imgUrls: [],//图片信息
    // licensePlate: undefined,//车牌号
    // typeCar: undefined,//车型
    // allRoyalty: 0,//总提成
    // saleUserCost: undefined,//销售人员提成
    // channelCost: undefined,//渠道人员费用
    // channelUserId: undefined,//渠道人员ID
    // cmmBuildPic: '',//施工图
    // cmmGroupPic: '',//人车合一照
    // jdFrameNoPic: '',
    // jdFrontPic: '',
    // jdRearPic: '',
    // jdDamagePic: '',
    // jdExpansionPic: '',
    // jdBlankPic: '',
    // jdPreLogoPic: '',
    // jdAfterLogoPic: '',
    // jdFinishPic: '',
    // jdDrivingLicensePic: '',
    // jdRunPic: '',
    // jdPolicyPic: '',
    // factoryNumber: '',//工厂编号
    // factoryName: '',//工厂产品名称
    // productType: '',//产品类型
    // no: '' // 订单单号，后端返回
  }


  formRef.value?.resetFields()

  formData.value.orderTime = Date.now();
}


</script>

